package com.lancoo.znbkxx.teacher.ui.fragment

//import com.lancoo.znbkxx.teacher.model.data.OptionX
//import com.lancoo.znbkxx.teacher.model.data.SubChildX
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebViewClient
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.QuestionAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.SubChildVoicePlayer
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtCommentListeningBinding
import com.lancoo.znbkxx.teacher.model.data.Child
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.utils.TimeUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.lancoo.znbkxx.teacher.widget.voicePlayer.VoicePlayer
import com.lancoo.znbkxx.teacher.widget.voicePlayer.VoicePlayer.PlayListener

/**
 * @author : Admin
 * @date   : 2019/8/5 21:20
 * @desc   :
 */
class ListeningFragment : BaseVMFragment<HardSolutionViewModel, FmtCommentListeningBinding>(),
        BaseQuickAdapter.OnItemChildClickListener, PlayListener {
    lateinit var adapter: QuestionAdapter
    private val foot by lazy { layoutInflater.inflate(R.layout.item_choice_footer, null) }
    val data = mutableListOf<Child>()

    //    val dataImg = mutableListOf<OptionX>()
    lateinit var player: VoicePlayer
    val type by lazy { requireArguments().getString("title") }
    val genre by lazy { viewModel.hardSolution.value!!.TkModel.GenreID }
    val list = mutableListOf<SubChildVoicePlayer>()

    companion object {
        private const val TITLE = "title"
        fun newInstance(title: String): ListeningFragment {
            val fragment = ListeningFragment()
            val bundle = Bundle()
            bundle.putString(TITLE, title)
            fragment.arguments = bundle
            return fragment
        }
    }


    override fun providerContext(): Any? {
        return activity
    }

    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_comment_listening
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        binding.tvQuestionname.text =
                if (viewModel.hardSolution.value!!.TkModel.GenreName.isBlank()) viewModel.hardSolution.value!!.TkModel.TypeName else viewModel.hardSolution.value!!.TkModel.GenreName
        binding.tvQuestionnum.text =
                "(共${viewModel.hardSolution.value!!.TkModel.TotalItemCount}个小题)"
        binding.tvFrom.text=HtmlUtils.setText("来源:<font color='#0099ff'>${viewModel.hardSolution.value!!.TkModel.Resource}</font>")
        if (type == "S" || type == "x" || type == "L") {
            initWebView()
        } else {
            binding.wv.visibility = View.GONE
        }
        initContent()
        initPlayer()
        initRecyclerView()
    }

    private fun initContent() {
        if (viewModel.hardSolution.value!!.TkModel.QuesAudio.Article.isNotBlank()) {
            binding.tvContent.visibility = View.VISIBLE
            binding.tvContent.text = HtmlUtils.setText(
                    getString(
                            R.string.aibk_audioscript,
                            viewModel.hardSolution.value!!.TkModel.QuesAudio.Article
                    )
            )
        } else {
            binding.tvContent.visibility = View.GONE
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        with(binding.wv.settings) {
            javaScriptEnabled = true
            loadWithOverviewMode = true
        }
        binding.wv.webViewClient = WebViewClient()
        binding.wv.webChromeClient = WebChromeClient()
        val body =
                if (type == "L") viewModel.hardSolution.value!!.TkModel.QuesBody else viewModel.hardSolution.value!!.TkModel.ChildList[0].ChildAsk
        WebStyleUtils.showWebViewCssStyle(activity, binding.wv, body, false)
    }


    private fun initRecyclerView() {
        binding.rv.layoutManager =
                LinearLayoutManager(requireContext()).apply { orientation = RecyclerView.VERTICAL }
        adapter = QuestionAdapter(
                viewModel.hardSolution.value!!.StuAllCount,
                requireArguments().getString("title"),
                genre,
                R.layout.item_question,
                data, lifecycle, player
        )
        adapter.onItemChildClickListener = this
        binding.rv.adapter = adapter
        adapter.addFooterView(foot)
    }

    @SuppressLint("SetTextI18n")
    private fun initPlayer() {
        val audioLength = viewModel.hardSolution.value!!.TkModel.QuesAudio.TimeLength
        val time = TimeUtils.getTime(audioLength.toInt())
        binding.include.findViewById<TextView>(R.id.tv_musicTime).text = "00:00/$time"
        val audioPath = viewModel.hardSolution.value!!.TkModel.QuesAudio.Path
        player = VoicePlayer(
                binding.include.findViewById(R.id.sb_musicProgress),
                audioPath,
                binding.include.findViewById(R.id.tv_musicTime),
                binding.include.findViewById(R.id.iv_audioIcon),
                true,
                true,
                false,
                this
        )
        lifecycle.addObserver(player)
    }

    override fun onFinishPlay() {
        player.rePlay()
    }

    override fun onStartPlay() {
        list.clear()
        list.addAll(adapter.getSubPlayer())
        list.forEach { it.pause() }
        player.play()
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        MyToast.showToast("ok")
    }

    override fun onStart() {
        super.onStart()
        data.clear()
        val sb = StringBuffer()
        val sbAnlysis = StringBuffer()
        val childxList = viewModel.hardSolution.value!!.TkModel.ChildList
        data.addAll(childxList)
        childxList.forEachIndexed { i, childx ->
            if (childx.ChildAnalysis.isEmpty()) {
                sbAnlysis.append("${i + 1}. ...略\n")
            } else {
                sbAnlysis.append("${i + 1}.${childx.ItemList[0].ItemAnalysis}\n")
            }
            if (type == "S" || type == "x") {
                val answerList = childx.ChildAnswer.split("\$、")
                answerList.forEachIndexed { j, answer ->
                    sb.append("${j + 1}.${answer.replace("$/", "或")}  ")
                }
            } else if (childxList.size == 1) {
                sb.append(childxList[0].ItemList[0].ItemAnswer)
            } else if (type == "G") {
                sb.append("${i + 1}.${childx.ItemList[0].ItemAnswer}\n")
            } else {
                sb.append("${i + 1}.${childx.ItemList[0].ItemAnswer}  ")
            }
        }
        foot.findViewById<TextView>(R.id.tv_answer).text = sb
        if (sbAnlysis.contains("略")) {
            foot.findViewById<TextView>(R.id.tv_analyze).text = "...略"
        } else {
            foot.findViewById<TextView>(R.id.tv_analyze).text = sbAnlysis
        }
    }
}